package io.noties.markwon.app.sample.ui;

import com.noties.markwon.utils.LogUtils;
import com.noties.markwon.utils.TextUtils;
import com.noties.markwon.wrapper.view.RecyclerView;

import io.noties.markwon.Markwon;
import io.noties.markwon.app.App;
import io.noties.markwon.app.ResourceTable;
import io.noties.markwon.app.readme.ReadMeActivity;
import io.noties.markwon.app.sample.MainAbility;
import io.noties.markwon.app.sample.Sample;
import io.noties.markwon.app.sample.SampleManager;
import io.noties.markwon.app.sample.SampleSearch;
import io.noties.markwon.app.sample.ui.adapt.CheckForUpdateItem;
import io.noties.markwon.app.sample.ui.adapt.SampleItem;
import io.noties.markwon.app.sample.ui.adapt.VersionItem;
import io.noties.markwon.app.samples.tasklist.TaskListMutateNestedSample;
import io.noties.markwon.app.utils.Cancellable;
import io.noties.markwon.app.utils.SampleUtilsKt;
import io.noties.markwon.app.utils.ThrowableUtils;
import io.noties.markwon.app.utils.UpdateUtils;
import io.noties.markwon.app.utils.ViewUtils;
import io.noties.markwon.app.widget.SearchBarCustom;
import io.noties.markwon.movement.MovementMethodPlugin;
import io.noties.markwon.sample.annotations.MarkwonArtifact;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.element.ElementScatter;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.utils.PacMap;
import ohos.utils.Pair;
import ohos.utils.Parcel;
import ohos.utils.Sequenceable;
import ohos.utils.net.Uri;

import org.jetbrains.annotations.NotNull;

/**
 * @author: yangrui
 * @function: SampleFragment
 * @date: 2021/3/23
 */
public class SampleListFragment extends Fraction {

    /**
     * TODO YR lack lib
     * private val adapt: Adapt = Adapt.create(DiffUtilDataSetChanged.create())
     */
    private RecyclerViewProvider adapt;
    private Markwon markwon;
    private Object type;
    private String search = "";

    private RecyclerScrollPosition pendingRecyclerScrollPosition = null;

    private Cancellable cancellable = null;

    private Cancellable checkForUpdateCancellable = null;

    private Component progressBar = null;

    private final VersionItem versionItem = new VersionItem();

    private final SampleManager sampleManager = App.sampleManager;

    private final PacMap pacMap;
    private RecyclerView recyclerView;
    private SearchBarCustom searchBar;

    private SampleListFragment(PacMap map) {
        this.pacMap = map;
        if (searchBar != null) {
            searchBar.clearFocus();
        }
    }

    private SampleListFragment.Type getType() {
        return parseType(pacMap);
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        markwon = markwon(getContext());
        return scatter.parse(ResourceTable.Layout_fragment_sample_list, container, false);
    }


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        initAppBar(getComponent());
        Context context = getContext();
        progressBar = getComponent().findComponentById(ResourceTable.Id_progress_bar);

        searchBar = (SearchBarCustom) getComponent().findComponentById(ResourceTable.Id_search_bar);
        searchBar.setOnSearchListener(new SearchBarCustom.OnSearchListener() {
            @Override
            public void onListener(String string) {
                search = string;
                fetch();
            }
        });

        recyclerView = (RecyclerView)

                getComponent().

                        findComponentById(ResourceTable.Id_recycler_view);
        recyclerView.setOrientation(Component.VERTICAL);
        adapt = new

                RecyclerViewProvider(getFractionAbility());
        recyclerView.setItemProvider(adapt);

        // TODO YR lack API
        // recyclerView.itemAnimator = DefaultItemAnimator()
        // recyclerView.setHasFixedSize(true)
        // recyclerView.adapter = adapt

        Optional<Sequenceable> state = pacMap.getSequenceable(STATE);

        String initialSearch = pacMap.getString(ARG_SEARCH);
        pacMap.remove(ARG_SEARCH);


        String search = null;

      /*  State sequenceableState = (State) state.get();
        pendingRecyclerScrollPosition = sequenceableState.recyclerScrollPosition;

        ArrayList<String> strings = new ArrayList<>();
        strings.add(sequenceableState.search);
        strings.add(initialSearch);

        search = strings.stream().findFirst()
                .orElse(null);
        */
        if (search != null) {
            searchBar.search(search);
        } else {
            fetch();
        }
    }

    @Override
    protected void onComponentDetach() {
        State state = new State(search, getRecyclerScrollPosition(recyclerView));
        // arguments?.putParcelable(STATE, state) && !cancellable.isCancelled
        if (cancellable != null) {
            if (!cancellable.isCancelled()) {
                cancellable.cancel();
            }
        }
        this.cancellable = null;
        super.onComponentDetach();

    }

    private void initAppBar(Component view) {
        Component appBar = view.findComponentById(ResourceTable.Id_app_bar);
        Image appBarIcon = (Image) appBar.findComponentById(ResourceTable.Id_app_bar_icon);
        Text appBarTitle = (Text) appBar.findComponentById(ResourceTable.Id_app_bar_title);
        Image appBarIconReadme = (Image) appBar.findComponentById(ResourceTable.Id_app_bar_icon_readme);
        // TODO YR lack api getBackStackEntryCount()
        boolean isInitialScreen = pacMap.getString(ARG_ARTIFACT) == null && pacMap.getString(ARG_TAG) == null;

        appBarIcon.setVisibility(isInitialScreen ? Component.HIDE : Component.VISIBLE);
        appBarIconReadme.setVisibility(!isInitialScreen ? Component.HIDE : Component.VISIBLE);

        Object type = this.getType();
        Pair<String, Integer> textAndBackground;

        if (type instanceof Type.Artifact) {
            textAndBackground = new Pair<>(SampleUtilsKt.getDisplayName(((Type.Artifact) type).getArtifact()),
                    ResourceTable.Graphic_bg_artifact);
        } else if (type instanceof Type.Tag) {
            textAndBackground =
                    new Pair<>(SampleUtilsKt.getTagDisplayName(((Type.Tag) type).getTag()), ResourceTable.Graphic_bg_tag);
        } else {
            appBarTitle.setText(ResourceTable.String_entry_name);
            textAndBackground = new Pair<>(appBarTitle.getText(), 0);
        }

        appBarTitle.setText(textAndBackground.f);
        if (textAndBackground.s != 0) {
            appBarTitle.setBackground(
                    ElementScatter.getInstance(getFractionAbility().getContext()).parse(textAndBackground.s));
        }
        if (isInitialScreen) {
            appBarIconReadme.setClickedListener((it) -> {
                Context context = getContext();
                Intent intent = ReadMeActivity.makeIntent(context);
                getFractionAbility().startAbility(intent);
            });
        } else {
            appBarIcon.setImageElement(
                    ElementScatter.getInstance(view.getContext()).parse(ResourceTable.Graphic_ic_arrow_back_white_24dp));
            appBarIcon.setClickedListener((it) -> {
                // TODO YR different api
                MainAbility mainAbility = (MainAbility) getFractionAbility();
                if (mainAbility != null) {
                    mainAbility.onBackPressedMainAbility();
                }
            });
        }

    }

    private void bindSamples(List<Sample> samples) {
        List<Object> items = new ArrayList<>();
        if (true) {
            items.add(new CheckForUpdateItem(this::checkForUpdate));
        }

        if (true) {
            items.add(versionItem);
        }

        for (Sample sample : samples) {
            items.add(new SampleItem(markwon, sample, sampleItemInterface));
        }
        getFractionAbility().getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override
            public void run() {
                adapt.setItems(items);
            }
        });

        // = adapt.recyclerView ?: return
        RecyclerView recyclerView = null;
        RecyclerScrollPosition scrollPosition = pendingRecyclerScrollPosition;

        LogUtils.i(SampleListFragment.class.getSimpleName(), String.valueOf(items.size()));

        if (scrollPosition != null) {
            pendingRecyclerScrollPosition = null;
            ViewUtils.onPreDraw(recyclerView, () -> {

                if (recyclerView.getLayoutManager() instanceof LayoutManager) {
                    recyclerView.scrollTo(scrollPosition.position, scrollPosition.offset);
                }
            });
        } else {
            ViewUtils.onPreDraw(recyclerView, () -> recyclerView.scrollTo(0));

        }

    }

    private void checkForUpdate() {
        if (checkForUpdateCancellable != null && !checkForUpdateCancellable.isCancelled()) {
            return;
        }
        progressBar.setVisibility(Component.VISIBLE);
        checkForUpdateCancellable = UpdateUtils.checkForUpdate(result -> getUITaskDispatcher().syncDispatch(() -> {
            processUpdateResult(result);
        }));
    }

    private void processUpdateResult(UpdateUtils.Result result) {
        Context context;
        if (this.getContext() == null) {
            return;
        } else {
            context = this.getContext();
        }
        progressBar.setVisibility(Component.HIDE);

        CommonDialog builder = new CommonDialog(context);
        builder.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        builder.setAlignment(LayoutAlignment.CENTER);

        if (result instanceof UpdateUtils.Result.UpdateAvailable) {
            String md = String.format("## Update available\n" +
                            "                    \n" +
                            "                    %1s -&gt; **%2s**\n" +
                            "                    \n" +
                            "                    Would you like to download it?", "BuildConfig.GIT_SHA",
                    ((UpdateUtils.Result.UpdateAvailable) result).revision);
            builder.setContentText(markwon.toMarkdown(md).toString());
            builder.setButton(CommonDialog.BUTTON1, "cancel", null);
            builder.setButton(CommonDialog.BUTTON2, "Download", (iDialog, i) -> {
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName("io.noties.markwon.app")
                        .withAbilityName(String.valueOf(Uri.parse(((UpdateUtils.Result.UpdateAvailable) result).url)))
                        .build();
                intent.setOperation(operation);
                getFractionAbility().startAbility(intent);

            });
        } else if (result instanceof UpdateUtils.Result.NoUpdate) {
            String md = String.format(" ## No update\n" +
                    "                    You are using latest version (**%1s**)", "BuildConfig.GIT_SHA");
            builder.setContentText(markwon.toMarkdown(md).toString());
            builder.setButton(CommonDialog.BUTTON1, "ok", null);

        } else if (result instanceof UpdateUtils.Result.Error) {
            String md = String.format("## Error\n" +
                    "```\n" +
                    "%1s\n" +
                    "```", ThrowableUtils.stackTraceString(((UpdateUtils.Result.Error) result).throwable));
            builder.setContentText(markwon.toMarkdown(md).toString());
            builder.setButton(CommonDialog.BUTTON1, "ok", null);
        }
        builder.show();
    }


    private final SampleItemInterface sampleItemInterface = new SampleItemInterface() {
        @Override
        public void openArtifact(MarkwonArtifact artifact) {
            openResultFragment(SampleListFragment.getInstance(artifact));
        }

        @Override
        public void openTag(String string) {
            openResultFragment(SampleListFragment.getInstance(string));
        }

        @Override
        public void openSample(Sample sample) {
            openFragment(SampleFragment.getInstance(sample));
        }
    };

    private void openResultFragment(SampleListFragment fragment) {
        openFragment(fragment);
    }

    private void openFragment(Fraction fragment) {
        // TODO YR different api .setCustomAnimations Window.ID_ANDROID_CONTENT
        getFractionAbility().getFractionManager()
                .startFractionScheduler()
                .add(ResourceTable.Id_container, fragment)
                .pushIntoStack(fragment.getClass().getSimpleName())
                .submit();
        LogUtils.e("CLICK TEST", "openFragment: " + fragment.getClass().getSimpleName());
    }

    public void fetch() {
        Object type = this.getType();
        SampleSearch sampleSearch = null;
        if (type instanceof Type.Artifact) {
            sampleSearch = new SampleSearch.Artifact(search, ((Type.Artifact) type).getArtifact());
        } else if (type instanceof Type.Tag) {
            sampleSearch = new SampleSearch.Tag(search, ((Type.Tag) type).getTag());
        } else {
            sampleSearch = new SampleSearch.All(search);
        }
        LogUtils.i("tag", sampleSearch.toString());
        // clear current && cancellable.isCancelled
        if (cancellable != null) {
            if (cancellable.isCancelled()) {
                cancellable.cancel();
            }
        }
        String text = sampleSearch.getText();

        cancellable = sampleManager.samples(sampleSearch, new SampleManager.Callback() {
            @Override
            public void callback(List<Sample> samples) {
                boolean addVersion = type instanceof SampleSearch.All && TextUtils.isEmpty(text);
                LogUtils.e("CLICK TEST", "samples.size(): " + samples.size());
                LogUtils.e("CLICK TEST", "samples.toString(): " + samples.toString());
                SampleListFragment.this.bindSamples(samples);
            }
        });
    }

    private static final String ARG_ARTIFACT = "arg.Artifact";
    private static final String ARG_TAG = "arg.Tag";
    private static final String ARG_SEARCH = "arg.Search";
    private static final String STATE = "key.State";

    // TODO YR duplication of name
    public static SampleListFragment getInstance() {
        return new SampleListFragment(new PacMap());
    }

    private static SampleListFragment getInstance(MarkwonArtifact artifact) {
        PacMap map = new PacMap();
        map.putString(ARG_ARTIFACT, artifact.name());
        return new SampleListFragment(map);
    }

    private static SampleListFragment getInstance(String tag) {
        PacMap map = new PacMap();
        map.putString(ARG_TAG, tag);
        return new SampleListFragment(map);
    }

    public static SampleListFragment getInstance(SampleSearch search) {
        PacMap map = new PacMap();
        if (search instanceof SampleSearch.Artifact) {
            map.putString(ARG_ARTIFACT, ((SampleSearch.Artifact) search).getArtifact().name());
        } else if (search instanceof SampleSearch.Tag) {
            map.putString(ARG_TAG, ((SampleSearch.Tag) search).getTag());
        }
        String text = search.getText();
        if (text != null) {
            map.putString(ARG_SEARCH, text);
        }
        return new SampleListFragment(map);
    }

    private static Markwon markwon(Context context) {
        return Markwon.builder(context)
                .usePlugin(MovementMethodPlugin.none())
                .build();
    }

    private static Type parseType(PacMap arguments) {
        String name = arguments.getString(ARG_ARTIFACT);
        String tag = arguments.getString(ARG_TAG);
        Type type;
        if (!TextUtils.isEmpty(name)) {
            MarkwonArtifact markwonArtifact = MarkwonArtifact.valueOf(name);
            type = new Type.Artifact(markwonArtifact);
        } else if (!TextUtils.isEmpty(tag)) {
            type = new Type.Tag(tag);
        } else {
            type = new Type.All();
        }
        return type;
    }


    class State implements Sequenceable {
        String search;
        final RecyclerScrollPosition recyclerScrollPosition;

        State(String search, RecyclerScrollPosition recyclerScrollPosition) {
            this.search = search;
            this.recyclerScrollPosition = recyclerScrollPosition;
        }

        public RecyclerScrollPosition getRecyclerScrollPosition() {
            return recyclerScrollPosition;
        }

        @Override
        public boolean marshalling(Parcel parcel) {
            return parcel.writeString(this.search);
        }

        @Override
        public boolean unmarshalling(Parcel parcel) {
            search = parcel.readString();
            return false;
        }

        @Override
        public String toString() {
            return "State{" +
                    "search='" + search + '\'' +
                    ", recyclerScrollPosition=" + recyclerScrollPosition +
                    '}';
        }
    }

    public class RecyclerScrollPosition implements Sequenceable {
        int position;
        int offset;

        RecyclerScrollPosition(int position, int offset) {
            this.position = position;
            this.offset = offset;
        }

        @Override
        public boolean marshalling(Parcel parcel) {
            if (!parcel.writeInt(this.position)) {
                return false;
            }
            return parcel.writeInt(this.offset);
        }

        @Override
        public boolean unmarshalling(Parcel parcel) {
            position = parcel.readInt();
            offset = parcel.readInt();
            return false;
        }
    }

    private RecyclerScrollPosition getRecyclerScrollPosition(RecyclerView recyclerView) {
        RecyclerView.ViewHolder holder = findFirstVisibleViewHolder(recyclerView);
        int position = holder == null ? 0 : holder.getAdapterPosition();
        int offset = holder == null ? 0 : holder.itemView.getTop();
        return new RecyclerScrollPosition(position, offset);
    }

    private RecyclerView.ViewHolder findFirstVisibleViewHolder(RecyclerView recyclerView) {
        if (recyclerView.getChildCount() > 0) {
            Component child = recyclerView.getComponentAt(0);
            return recyclerView.findContainingViewHolder(child);
        }
        return null;
    }


    abstract static class Type {

        static final class Artifact extends SampleListFragment.Type {
            @NotNull
            private final MarkwonArtifact artifact;

            @NotNull
            final MarkwonArtifact getArtifact() {
                return this.artifact;
            }

            Artifact(@NotNull MarkwonArtifact artifact) {
                super();
                this.artifact = artifact;
            }
        }

        static final class Tag extends SampleListFragment.Type {
            @NotNull
            private final String tag;

            @NotNull
            final String getTag() {
                return this.tag;
            }

            Tag(@NotNull String tag) {
                super();
                this.tag = tag;
            }
        }

        static final class All extends SampleListFragment.Type {

            private All() {
                super();
            }

        }

    }


    class RecyclerViewProvider extends BaseItemProvider {

        private final Ability slice;
        List<Object> dataList;
        private final String SIMPLE_ITEM_TAG = "simpleItemTag";

        RecyclerViewProvider(Ability slice) {
            this.slice = slice;
        }

        void setItems(List<Object> dataList) {
            this.dataList = dataList;
            notifyDataChanged();
        }

        @Override
        public int getCount() {
            return dataList == null ? 0 : dataList.size();
        }

        @Override
        public Object getItem(int position) {
            if (dataList != null && position >= 0 && position < dataList

                    .size()) {
                return dataList.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
            Component cpt;
            Object data = dataList.get(position);
            if (position == 0) {
                cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_adapt_version, null, false);
                cpt.setClickedListener((it) -> {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri contentUrl = Uri.parse(TextUtils.getHttps() + "github.com/noties/Markwon/blob/master/CHANGELOG.md");
                    intent.setUri(contentUrl);
                    getFractionAbility().startAbility(intent);
                });
                boolean isInitialScreen = pacMap.getString(ARG_ARTIFACT) == null && pacMap.getString(ARG_TAG) == null;
                cpt.setVisibility(!isInitialScreen ? Component.HIDE : Component.VISIBLE);
            } else if (position == 1) {
                cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_adapt_check_for_update, null, false);
                boolean isInitialScreen = pacMap.getString(ARG_ARTIFACT) == null && pacMap.getString(ARG_TAG) == null;
                cpt.setVisibility(!isInitialScreen ? Component.HIDE : Component.VISIBLE);
                cpt.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component it) {
//                        checkForUpdate();
                        new ToastDialog(cpt.getContext()).setText("Check for update").show();
                        showErrorDialog(cpt.getContext());
                    }
                });
            } else {
                cpt = simpleItem(convertComponent, (SampleItem) data);
                cpt.setTag(SIMPLE_ITEM_TAG);
            }
            return cpt;
        }

        @NotNull
        private Component simpleItem(Component convertComponent, SampleItem data) {
            Component cpt;
            if (convertComponent == null || !SIMPLE_ITEM_TAG.equals(convertComponent.getTag())) {
                cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_adapt_sample, null, false);
            } else {
                cpt = convertComponent;
            }
            Sample sample = data.getSample();

            Text title = (Text) cpt.findComponentById(ResourceTable.Id_title);

            try {
                title.setText(sample.getTitle());
            } catch (Exception e) {
                e.printStackTrace();
            }

            Text description = (Text) cpt.findComponentById(ResourceTable.Id_description);
            description.setText(sample.getDescription());


            DirectionalLayout artifactFlowLayout =
                    (DirectionalLayout) cpt.findComponentById(ResourceTable.Id_artifacts);
            List<MarkwonArtifact> artifacts = sample.getArtifacts();
            int viewCount = artifacts.size();
            int childCount = artifactFlowLayout.getChildCount();
            if (viewCount > childCount) {
                for (int i = 0; i < viewCount - childCount; i++) {
                    Component inflate =
                            LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_view_artifact, null, false);
                    artifactFlowLayout.addComponent(inflate);
                }
            } else {
                for (int i = viewCount; i < childCount; i++) {
                    artifactFlowLayout.getComponentAt(i).setVisibility(Component.HIDE);
                }
            }
            for (int i = 0; i < artifacts.size(); i++) {
                Component childAt = artifactFlowLayout.getComponentAt(i);
                MarkwonArtifact markwonArtifact = artifacts.get(i);
                if (childAt instanceof Text) {
                    ((Text) childAt).setText(SampleUtilsKt.getDisplayName(markwonArtifact));
                    childAt.setVisibility(Component.VISIBLE);
                }
                childAt.setClickedListener((it) -> {
                    data.sampleItemInterface.openArtifact(markwonArtifact);
                });
            }

            DirectionalLayout tagsFlowLayout = (DirectionalLayout) cpt.findComponentById(ResourceTable.Id_tags);
            List<String> tags = sample.getTags();
            int viewCount1 = tags.size();
            int childCount1 = tagsFlowLayout.getChildCount();
            if (viewCount1 > childCount1) {
                for (int i = 0; i < viewCount1 - childCount1; i++) {
                    Component inflate =
                            LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_view_tag, null, false);
                    tagsFlowLayout.addComponent(inflate);
                }
            } else {
                for (int i = viewCount1; i < childCount1; i++) {
                    tagsFlowLayout.getComponentAt(i).setVisibility(Component.HIDE);
                }
            }
            for (int i = 0; i < tags.size(); i++) {
                Component childAt = tagsFlowLayout.getComponentAt(i);
                String tag = tags.get(i);
                if (childAt instanceof Text) {
                    ((Text) childAt).setText(SampleUtilsKt.getTagDisplayName(tag));
                    childAt.setVisibility(Component.VISIBLE);
                }

                childAt.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        data.sampleItemInterface.openTag(tag);
                    }
                });
            }

            cpt.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    data.sampleItemInterface.openSample(data.getSample());
                    LogUtils.e("CLICK TEST", "openSample: " + data.getSample());
                }
            });

            return cpt;
        }
    }


    public void showErrorDialog(Context context) {
        String md = String.format("Updated error.\nPlease try it later...");
        CommonDialog commonDialog = new CommonDialog(context);
        Component component = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_dialog_custom_layout, null, false);
        commonDialog.setContentCustomComponent(component);
        commonDialog.setSize(900, 500);
//        commonDialog.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        commonDialog.show();

        Text updateText = (Text) component.findComponentById(ResourceTable.Id_update_text);
        Button dismissButton = (Button) component.findComponentById(ResourceTable.Id_dismiss);
        Button okButton = (Button) component.findComponentById(ResourceTable.Id_ok);

        updateText.setText(md);

        okButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialog.hide();
            }
        });

    }


    public interface SampleItemInterface {

        /**
         * openArtifact
         *
         * @param markwonArtifact markwonArtifact
         */
        void openArtifact(MarkwonArtifact markwonArtifact);

        /**
         * open item by tag
         *
         * @param tag Filter tag
         */
        void openTag(String tag);

        /**
         * openSample
         *
         * @param sample openSample
         */
        void openSample(Sample sample);
    }

}
